<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Do you want to play?</title>
 <link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.7.0/build/reset/reset-min.css"/>
    <link type="text/css" rel="stylesheet" href="/static/jqueryui-theme/jquery-ui-1.7.2.custom.css"/>
    <link type="text/css" rel="stylesheet" href="/static/css/app.css"/>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <script type="text/javascript" src="/static/lib/jquery.scrollTo-1.4.2-min.js"></script>
    <script type="text/javascript" src="/static/lib/microtemplate.js"></script>
    <script type="text/javascript" src="/static/js/frontV3.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
 <script type="text/javascript">
 			
      google.setOnLoadCallback(init);
    </script>
<script type="text/javascript">
	  var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var map;
var markersArray = [];
var infowindow;
var gamename;
var gametype = 0;//the default is Any
var gamepostion;
var gameaddress;

var ICON_TYPES = {
  1: '/static/images/classicfootball.png',//'Football',
  2: '/static/images/basketball.png',//'Basketball',
  3: '/static/images/tennis.png',//'Tennis',
  4:'/static/images/pingpong.png', //'Pingpong',
  5: '/static/images/baseball.png',//'Baseball',
  6: '/static/images/golf.png',//'Golf',
  7: '/static/images/american_football.png'//'American Football'
};
 
      
function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateMarkerAddress(responses[0].formatted_address);
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}


function updateMarkerStatus(str) {
  document.getElementById('markerStatus').innerHTML = str;
}

function showname(str){
	document.getElementById('gamename').innerHTML =  str;
	gamename = str;
}

function showtype(str){
	document.getElementById('gametype').innerHTML =  str;
	gametype = str;
	
}

function showCurrentGameAddress(pos){
	
	geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateGameAddress(responses[0].formatted_address);
    } else {
      updateGameAddress('Cannot determine address at this location.');
    }
  });
}

function updateGamePosition(latLng) {
  document.getElementById('gameadress').innerHTML = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
}

function updateGameAddress(str) {
  document.getElementById('gameaddress').innerHTML = str;
  gameaddress = str;
}

function updateMarkerPosition(latLng) {
  document.getElementById('info').innerHTML = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
  gamepostion = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

function updateMarkerAddress(str) {
  document.getElementById('address').innerHTML = str;
 
  gameaddress = str;
}

function saveGame(){

	//document.write(gamename +"\n"+gametype+"\n"+gameaddress+"\n"+gamepostion);
	if(gamename == null )
	{
	alert("gamename can not be empty!")
	return false;
	}
	latlng = gamepostion.split(',');
	var savequery = { "name": gamename, "type": gametype, "latitude": latlng[0],"longitude":latlng[1]};
//	alert([latlng[0],latlng[1]].join(","))
//	alert(savequery.address)
	
	
		$.ajax({
  type: 'POST',
  dataType: 'json',
  url:'/s/save',
  data: savequery,
   beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType("application/j-son;charset=UTF-8");
  }
 },
  success: function(obj,textStatus){
  //	alert(textStatus)
  	 alert(obj.name +" saved " + obj.savedSuccess)
  //	 alert("gametype " + GAME_TYPES[obj.type])
  //	 alert(obj.latitude)
     var pos = new google.maps.LatLng(obj.latitude, obj.longitude);
     geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
       alert("new game address: "  + responses[0].formatted_address)
    } else {
      alert('Cannot determine address at this location.');
    }
  });
     
    
  for (var i = 0; i < obj.results.length; i++) {
          var result = obj.results[i];
         
        }
  },
  error:function(data, textStatus, XMLHttpRequest){
      alert(textStatus);
      alert(data.status);
 
  	
  },
  complete: function(obj){
   
  }});
}
function showMarker(result) {  
  	var icon = new google.maps.MarkerImage(result.icon,
     null, null, null, new google.maps.Size(64, 64) );
  
  var resultLatLng = new google.maps.LatLng(result.lat, result.lng);
  
  var marker = new google.maps.Marker({
  	position: resultLatLng, 
    icon: icon,
    title: result.name
  });
  
  google.maps.event.addListener(marker, 'click', (function(result) {
    return function() {
      if (g_listView && result.listItem) {
        $.scrollTo(result.listItem, {duration: 1000});
      } else {
        var infoHtml = tmpl('tpl_result_info_window', { result: result });
        
        map.openInfoWindowHtml(marker.getLatLng(), infoHtml, {
          pixelOffset: new GSize(icon.infoWindowAnchor.x - icon.iconAnchor.x,
                                 icon.infoWindowAnchor.y - icon.iconAnchor.y)});
      }
    };
  })(result));
  
  return marker;
}

function showAll(){

	
		$.ajax({
  type: 'get',
  dataType: 'json',
  url:'/s/showall',
  data: "",
   beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType("application/j-son;charset=UTF-8");
  }
 },
  success: function(objs,textStatus){
  //	alert(textStatus)
  	alert("There are already "+objs.count+" games waiting for you!")
  	//alert(objs)
  	//alert(objs.results.length)
    
       var filtertype = document.getElementById('mode').value;
       var count = 0;
             for (var i = 0; i < objs.results.length; i++) {
         
          var result = objs.results[i];
          
           if( filtertype == 0 || filtertype == result.game_type){
          result.icon = ICON_TYPES[result.game_type];
// alert("create game marker: " + result.game_type)
         // var resultLatLng = new google.maps.LatLng(result.lat, result.lng);
          

       //   newBounds.extend(resultLatLng);
					
          // Create result marker.
          result.marker = showMarker(result);
        //  alert(result.lat)
         // alert(result.lng)
    //      alert("create game marker: " + result.game_type)
          result.marker.setMap(map);
          
        markersArray.push(result.marker);
        count = count + 1;}
        
        }
     alert( count + " " + GAME_TYPES[filtertype])
 
  },
  error:function(data, textStatus, XMLHttpRequest){
   //   alert(textStatus);
 //     alert(data.status);
 
  	
  },
  complete: function(obj){
   
  }});
}
function subscribeLBS(){
 

  var phone_number = document.getElementById('phone_number').value;
  var query_data = { "phone_number" : phone_number };
  
  //alert(document.getElementByName('phone_number').value);
 //  alert($("#phone_number").value);
 
		$.ajax({
  type: 'POST',
  dataType: 'json',
  url:'/s/lbs',
  data: query_data,
   beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType("application/j-son;charset=UTF-8");
  }
 },
  success: function(obj,textStatus){
  	if( textStatus == "success")
  	 alert("You are at the phone's location!")
   //  map.setZoom(12)
     var pos = new google.maps.LatLng(obj.latitude,obj.longitude)
     geocodePosition(pos)
     
     map.setZoom(15);
      //the phone's owner's marker is the first marker in the map
     markersArray[0].setPosition(pos)
  	 map.setCenter(pos);
  	 var parser;
  	 var xmlDoc;
  	 if (window.DOMParser)
 	 {
 			  parser=new DOMParser();
 			  xmlDoc=parser.parseFromString(obj,"text/xml");
 		 }
		else // Internet Explorer
  {
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
 		  xmlDoc.async="false";
 			xmlDoc.loadXML(obj); 
  }
  xmlObj=xmlDoc.documentElement;

            
  },
  error:function(data, textStatus, XMLHttpRequest){
      alert(textStatus);
     	
  },
  complete: function(obj){
   
  }});
}

var i = 0;


function addMarker(event) {
	var iconimage;
	if( gametype != null && gametype > 0)
  {
  	iconimage = new google.maps.MarkerImage(
       ICON_TYPES[gametype],
       // the following code works!!!
                     //   new google.maps.Size(84,84) // The Size works
                       //The following line breaks iot with dynamic value    
                       //new google.maps.Size(myIconArray.icon[myData.name_etp].size) 


       //new google.maps.Point(0, 0), // The origin
       //new google.maps.Point(13,29) // The anchor
       null, null, null, new google.maps.Size(64, 64) //just using scale size works, using size of icon just only set the frame size of an icon
      );
  }
else
  	iconimage = "http://maps.google.com/mapfiles/kml/paddle/blu-stars.png";
  marker = new google.maps.Marker({
  	cursor: "move",
    position: event.latLng,
    map: map,
    icon: iconimage,
    draggable:true
  });
  markersArray.push(marker);

  addMarkerListener(marker);
  marker.setMap(map);
  i = markersArray.length;
  marker.setTitle('game '+ i.toString());
  


var iwform =  					"<div id='game' value='"+i+"'>"+
											//	"<form  autocomplete='off'>"+
                       "Name:<input type='text' name='name' onchange='showname(this.value)' onclick='showname(this.value)' onmouseout='showname(this.value)' onfoucs='showname(this.value)'/><br /><br /> " +
                         "Game content:<div  name='content'><b><textarea rows='9' cols='20'></textarea></b><div><br />" +
                         "<label for='type'>Type:</label><select name='type' onChange='showtype(this.value)' onblur='showtype(this.value)'>" +
                         "<option value='0'>Any</option>" +
                            "<option value='1'>Footballl</option>" +
                          "<option value='2'>Basketball</option>" +
                             "<option value='3'>Tennis</option>" +
                              "<option value='4'>Pingpong</option>" +
                               "<option value='5'>Baseball</option>" +
                                "<option value='6'>Golf</option>" +
                                "<option value='7'>American Football</option>" +
                         "</select>" +
                         "<input type='submit' value='Save' onclick='saveGame()'/>"+
                         "</div>";
								
/*"<form action='\addDB' method='post'>"
                + "<input type=\'hidden\' name=\'latlng\' value="+document.getElementById('address').innerHTML+">"
                + "<label for='place'>Name:</label><input id='id_place' type='text' name='place' size='15' value=""/><br />"
                + "<input type='submit' value='Save'/>"
                + "</form>";*/
  var message = marker.getTitle();
  var infowindow = new google.maps.InfoWindow(
      { content: iwform,
        size: new google.maps.Size(100,200)
      });
      google.maps.event.addListener(infowindow,'content_changed',function(){
          // var content=this.getContent();
         //  alert(content);
					//var myRegExp  =  /<a>(.+)<\/a>/;
			//		var root = document.getElementById('game 2');
			//	alert(root);
					 						//alert(content.match(myRegExp)[1]);
					 					
					 						geocodePosition(infowindow.getPosition())
      });
            google.maps.event.addListener(infowindow,'domready',function(){
          // var content=this.getContent();
         //  alert(content);
					//var myRegExp  =  /<a>(.+)<\/a>/;
			//		var root = document.getElementById('game 2');
			//	alert(root);
					 						//alert(content.match(myRegExp)[1]);
					 						
					 					
					 						geocodePosition(infowindow.getPosition())
      });
  google.maps.event.addListener(marker, 'click', function() {

    infowindow.setContent(iwform);
    infowindow.open(map,this);
    
  //  showCurrentGameAddress(this.getPostion());
  });
    
  /*var div = document.createElement("div"); 
var a = document.createElement("a"); 
a.innerHTML = "Edit Marker"; 
div.appendChild(a); 
google.maps.event.addDomListener(a, "click", function() 
{ marker.setDraggable(true); }); 
MyInfoWindow.setContent(div); */


}

function addMarkerListener(marker){
 // Add dragging event listeners.
  //google.maps.event.addListener(marker, 'dragstart', function() {
    //updateMarkerAddress('Dragging...');
 // });
  
  google.maps.event.addListener(marker, 'drag', function() {
   // updateMarkerStatus('Dragging...');
    updateMarkerPosition(marker.getPosition());
  });

  google.maps.event.addListener(marker, 'dragend', function() {
   // updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());
  });
  
  google.maps.event.addListener(marker, 'rightclick', function() {
   // map.removeOverlay(marker);
    marker.setMap(null);
    
  });
    
}
		
function initialize() {
	
  var latLng = new google.maps.LatLng(29.76, -95.37);
  map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 16,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var marker = new google.maps.Marker({
    position: latLng,
    title: 'Current location',
    map: map,
    draggable: true
  });
 var message = "I am Here";
   var infowindow = new google.maps.InfoWindow(
      { content: message,
        size: new google.maps.Size(50,50)
      });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
 
  markersArray.push(marker);

  // Update current position info.
  updateMarkerPosition(latLng);
  geocodePosition(latLng);
  
    // Add click new Marker event listeners.
   google.maps.event.addListener(map, 'click', addMarker);
   
         
      
       
  addMarkerListener(marker);
  marker.setMap(map);
  directionsDisplay = new google.maps.DirectionsRenderer();
  
    directionsDisplay.setMap(map);

var infohtml = 				 "<table>" +
                         "<tr><td>Name:</td> <td><input type='text' name='name'/> </td> </tr>" +
                         "<tr><td>Address:</td> <td><input type='text' name='address'/></td> </tr>" +
                         "<tr><td>Type:</td> <td><select name='type'>" +
                         "<option value='bar' SELECTED>bar</option>" +
                         "<option value='restaurant'>restaurant</option>" +
                         "</select> </td></tr>" +
                         "<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
   Eidtinfowindow = new google.maps.InfoWindow(
      { content: infohtml,
        size: new google.maps.Size(50,50)
      });
}

// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);

 function calcRoute() {
    map.setZoom(2);
    showAll();
  }
</script>
<style type="text/css" media="screen"> 
@import "general.css"; /* Mostly just text styling. */
/* 
body {
	margin: 0px; padding:0px; /* Need to set body margin and padding to get consistency between browsers. 
	float:left;
	text-align:center; /* Hack for IE5/Win 
	}
	*/

</style> 
</style> 
</head>
<body>
  <style>
#mapCanvas {
	width:70%;
	height:70%;
	float:left;
	margin:0px auto; /* Right and left margin widths set to "auto" */
	text-align:left; /* Counteract to IE5/Win Hack */
	padding:0px;
	/*border:0px dashed #333;*/
	background-color:#eee;
	}
  #infoPanel {
    float: left;
    margin-left: 10px;
  }
  #infoPanel div {
    margin-bottom: 5px;
  }
  </style>
   <div id="login-bar">
      {% if current_user %}
        <strong>{{ current_user.email }}</strong>
        &nbsp;|&nbsp;
        <a href="{% logout_url %}">Sign out</a>
      {% else %}
        <a href="{% login_url %}">Sign in</a>
      {% endif %}
    </div>

      <div id="container">
      	<div id="header" class="clearfix">
        <div id="logo">
          <div id="slogan">
          </div>
        </div>
        
        <form action="" onSubmit="doGeocodeAndSearch(); return false;">
          <div id="search-container">
            <p><label for="search-query">Search for games near:</label></p>
            <input id="search-query" type="search" />

            <input type="submit" value="Search"/>
            
            <img id="loading" src="/static/images/loading.gif" alt="Loading..."/>
          </div>
          
          <div id="advanced-options-container">
            <div id="search-error">&nbsp;</div>
            <a id="advanced-options-toggle" href="#">Advanced Options</a>
            
            <div id="advanced-options">
              <div class="row clearfix">
                
              </div>
              <div class="row clearfix">
                <label for="search-game-type">Game type:</label>
                <select id="search-game-type">
                </select>
              </div>
            </div>
          </div>
        </form>
      	</div>       
        
          
        
      
      </div>
     
   <div id="mapCanvas"></div>
<div style="padding:10px;margin:20px;border-width:2px;font-size:20; color:rgb(0,0,255)"> 
<b> Which game do you want to play: </b> 
<select id="mode" onChange="calcRoute();">
</select> 
<br />
 
<br />
<br />
 <p>
   <font size="-1">Please enter your mobile phone number, the number will subscribe for geolocation and SMS services,then you can realtime sync your current location and get SMS from other players.</font></p>
							<p>&nbsp;</p> 
							<form name="phonenumber" method="post" action="" onReset="return confirm('Do you really want to use the SandBox number?')">
							<P>Track Phone Number:<INPUT type="text" id="phone_number" name="phone_number" value="19175550001"><BR></p>
							 <INPUT type="button" value="Subscribe LBS" onclick="subscribeLBS()"> <INPUT type="reset" value="Use SandBox number">
							</form>
</div> 


 
  <!--  <div id="infoPanel">
    <div align="left" font-size="15"><b>Marker status:</b>
    </div>
    <div id="markerStatus">
      <div align="left"><i>Click and drag the marker.</i></div>
    </div>
    <div align="left"><b>Current position:</b>
    </div>
    <div id="info"></div>
    <div align="left"><b>Closest matching address:</b>
    </div>
   <div id="address"></div>
  </div>   -->
  <input style="height: 25px; width: 200px;font:big" onclick="clearOverlays();" type=button value="Clear all games already shown"/> 
   <div id="infoPanel" style="margin:20px;color:rgb(0,0,255);">
   	<form action="/s/save" method="post">
    <div align="left" font-size="15"><b>Current Game Name:</b>
    </div>
    <div id="gamename">
      <div align="left"><i><br /></i></div>
    </div>
     <div align="left" font-size="15"><b>Game position:</b><br />
    </div>
    <div id="info">
    <div align="left"><b><br /></b></div>
    </div>
      <div align="left" font-size="15"><b>Game type:</b><br />
    </div>
    <div id="gametype">
    <div align="left"><b><br /></b></div>
    </div>
     <div align="left" font-size="15"><b>Closest matching address:(You can drag your new marker a little to update the address)</b><br />
    </div>
    <div id="address"></div>
    <div align="left"><b><br /></b>
    </div>
    <br /> 
 
</form> 
  </div>   
  

</body>
</html>